package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.TestSoulApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author:DD
 * @Date :2021/10/6 12:07
 */
@Service
@Slf4j
public class TestSoulService {
    @Reference
    private TestSoulApi testSoulApi;

    /**
     * 提交测试数据
     *
     * @param answerVos
     * @return
     */
    public String submitTest(List<AnswersVo> answerVos) {
        Long userId = UserHolder.getUserId();
        //遍历答题选项集合，根据选项id 查出 4项属性的分数
        Report report = testSoulApi.findScore(answerVos);
        //根据各项得分情况 得出性格类型
        double abstractScore = report.getAbstractScore();
        double extrovertedScore = report.getExtrovertedScore();
        double judgmentScore = report.getJudgmentScore();
        double rationalScore = report.getRationalScore();
        double score = abstractScore * 0.05 + extrovertedScore * 0.7 + judgmentScore * 0.15 + rationalScore * 0.1;
        log.debug("score的得分为:"+score);
        //查表，得出性格类型
        Conclusion conclusion = testSoulApi.findConclusion(score);
        //找出一个问题Id
        String questionId = answerVos.get(0).getQuestionId();
        //得出情况之后，将根据UserId将结论存入报告表，返回报告Id
        report.setConclusionId(conclusion.getId());
        report.setUserId(userId);
        ObjectId reportId = new ObjectId();
        report.setId(reportId);
        testSoulApi.saveReport(report, userId, questionId);
        //查询Questionnaire的星级，判断并解锁下一阶段的试题
        testSoulApi.unlockNextQuestionnaire(questionId, userId);
        return reportId.toHexString();
    }

    /**
     * 根据用户id获取调查问卷数据
     *
     * @return
     */
    public List<QuestionnaireVo> findQuestionnaireListByUserId() {
        //创建封装数据的集合
        List<QuestionnaireVo> qvoList = new ArrayList<>();
        //获取用户id
        Long userId = UserHolder.getUserId();
        //根据用户id从userquestionnairestatus获取初级,中级,高级的锁定解锁状态
        UserQuestionnaireStates questionnaireStates = testSoulApi.getQuestionnaireStatus(userId);
        //去调查问卷表获取全部的数据
        List<Questionnaire> questionnaireList = testSoulApi.findAllQuestionnaire();
        log.debug("调查问卷表的questionnaireList所有数据:" + questionnaireList);
        //遍历调查问卷集合数据
        if (!StringUtils.isEmpty(questionnaireList)) {
            for (Questionnaire questionnaire : questionnaireList) {
                QuestionnaireVo qvo = new QuestionnaireVo();
                Integer star = questionnaire.getStar();
                //如果级别不同赋值不同锁定状态
                switch (star) {
                    case 2:
                        qvo.setIsLock(questionnaireStates.getPrimaryStatus());  //初级灵魂题的锁定状态
                        break;
                    case 3:
                        qvo.setIsLock(questionnaireStates.getMiddleStatus());  //初级灵魂题的锁定状态
                        break;
                    case 5:
                        qvo.setIsLock(questionnaireStates.getHighStatus());  //初级灵魂题的锁定状态
                        break;
                    default:
                        qvo.setIsLock(0);
                        break;
                }
                //把questionnaire的数据赋值给QuestionnaireVo
                BeanUtils.copyProperties(questionnaire, qvo);
                qvo.setId(questionnaire.getId().toHexString());
                //此时只剩下List<Question> qusetion 集合没有数据List<QuestionVo> questions
                //根据调查问卷表的发布id去问题表获取其问题数据
                List<Question> questionList = testSoulApi.findQuestionById(questionnaire.getId());
                List<QuestionVo> questionVoList = new ArrayList<>();
                log.debug("问题表的所有数据:" + questionList);
                //遍历问题集合
                if (!StringUtils.isEmpty(questionList)) {
                    for (Question question : questionList) {
                        QuestionVo qv = new QuestionVo();
                        BeanUtils.copyProperties(question, qv);
                        qv.setId(question.getId().toHexString());
                        //这时候qv的OptionVO是空的
                        //根据问题发布id去option表去获取选项数据
                        List<Option> optionList = testSoulApi.findOption(question.getId());
                        log.debug("option表的optionList的数据:" + optionList);
                        List<OptionVo> optionVoList = new ArrayList<>();
                        //把获取到集合数据赋值给question
                        for (Option option : optionList) {
                            OptionVo optionVo = new OptionVo();
                            BeanUtils.copyProperties(option, optionVo);
                            optionVo.setId(option.getId().toHexString());
                            optionVoList.add(optionVo);
                        }
                        qv.setOptions(optionVoList);
                        questionVoList.add(qv);
                    }
                }
                //把集合数据赋值给qvo的List<Question> qusetion
                qvo.setQuestions(questionVoList);
                //根据问卷的查询出的问卷的星级与用户的userId，在报告表中查询登录用户不同星级问卷的不同报告id返回
                String reportId = testSoulApi.getReportId(userId,star);
                qvo.setReportId(reportId);
                //添加到qvoList集合
                qvoList.add(qvo);
            }
        }
        //返回数据
        return qvoList;
    }


    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 测灵魂查看结果
     * id:报告id
     */
    public ReportVo findReportById(String id) {

        ReportVo reportVo = new ReportVo();

        //根据id 从鉴定表中查询维度值
        Report report = testSoulApi.findReportById(id);

        //封装维度值

        List<DimensionsVo> list = new ArrayList<>();

        DimensionsVo d1 = new DimensionsVo("抽象",report.getAbstractScore()+"%");

        DimensionsVo d2 = new DimensionsVo("外向",report.getExtrovertedScore()+"%");
        DimensionsVo d3 = new DimensionsVo("判断",report.getJudgmentScore()+"%");
        DimensionsVo d4 = new DimensionsVo("理性",report.getRationalScore()+"%");
        list.addAll(Arrays.asList(d1,d2,d3,d4));



        reportVo.setDimensions(list);



        //***************************************************************

        //从report对象中获取conclusionId
        Object conclusionId = report.getConclusionId();

        //根据conclusionId，查询根据conclusion对应的信息
        Conclusion conclusion = testSoulApi.findConclusionById(conclusionId);

        BeanUtils.copyProperties(conclusion, reportVo);

        //***************************************************************

        //遍历查询conclusion表，获取conclusionId相同的userId放入到集合中
        List<Long> userIds = testSoulApi.findSimilarYou(conclusionId, UserHolder.getUserId());



        List<SimilarYou> similarYouList = new ArrayList<>();

        //获取推荐用户信息
        for (Long userId : userIds) {
            UserInfo userInfo = userInfoApi.findUserInfoById(userId);
            SimilarYou similarYou = new SimilarYou();
            similarYou.setId(userInfo.getId().intValue());
            similarYou.setAvatar(userInfo.getAvatar());
            similarYouList.add(similarYou);
        }

        //设置参数
        reportVo.setSimilarYou(similarYouList);
        //*****************************************************************
        return reportVo;
    }
}
